#include "mongoose.h"
#include "wyhash.h"
#include <fstream>
#include <sstream>
#include <string>
using	namespace	std;

static const char *s_web_root = "files";

static void fn(struct mg_connection *c, int ev, void *ev_data) {
    if (ev == MG_EV_HTTP_MSG) {
        struct mg_http_message *hm = (struct mg_http_message *) ev_data;
        char	knowledge[1024], name[256], password[256],	join[512];
        if(mg_http_get_var(&hm->body,	"knowledge", knowledge,	1023)>=0
        &&mg_http_get_var(&hm->body,	"name", name,	256)>=0
        &&mg_http_get_var(&hm->body,	"password", password,	256)>=0) {
        	strcpy(join,name);
        	strcat(join,password);
        	time_t	t=time(NULL);
        	ofstream	fo("files/knowledge.xls",ios::app);
        	fo<<knowledge<<'\t'<<name<<'\t'<<hex<<wyhash(join,strlen(join),0,_wyp)<<'\t'<<ctime(&t);
        	fo.close();
        	FILE	*f=fopen("files/index.html","rb");
        	fseek(f,0,SEEK_END);
        	string	s;	s.resize(ftell(f));
        	fseek(f,0,SEEK_SET);
        	fread(s.data(),s.size(),1,f);
        	fclose(f);
            mg_http_reply(c, 200, NULL, "%s", s.c_str());
        } else {
            struct mg_http_serve_opts opts = {.root_dir = s_web_root};
            mg_http_serve_dir(c, (mg_http_message*)ev_data, &opts);
        }
    }
}

int main(int ac,	char	**av) {
    struct mg_mgr mgr;
    mg_mgr_init(&mgr);
    printf("listening on %s\n",av[1]);
    mg_http_listen(&mgr,av[1], fn, NULL);
    for (;;) mg_mgr_poll(&mgr, 100);
    mg_mgr_free(&mgr);
    return 0;
}
